package com.ejlchina.tool.network

import android.content.Context
import android.content.SharedPreferences
import java.util.concurrent.TimeUnit

class Token(
    var accessToken: String,
    var refreshToken: String = "",
    var expiresIn: Int = 0,
    var expiresAt: Long = -1,
    var domain: String = ""

) {

    fun saveToSp(context:Context): Boolean {
        val now = System.currentTimeMillis() / 1000
        return tokenSp(context).edit()
            .putString("accessToken", accessToken)
            .putString("refreshToken", refreshToken)
            .putLong("expiresAt", expiresIn + now - 60)
            .putLong("refreshExpiresAt", TimeUnit.DAYS.toSeconds(7) + now - 60)
            .commit()
    }

    fun isValid(): Boolean {
        return expiresAt < 0 || expiresAt > System.currentTimeMillis() / 1000
    }


    companion object {

        fun fromSp(context:Context): Token? {
            val sp = tokenSp(context)
            val accessToken = sp.getString("accessToken", null)
            val refreshToken = sp.getString("refreshToken", null)
            if (accessToken == null || refreshToken == null) {
                return null
            }
            val refreshExpiresAt = sp.getLong("refreshExpiresAt", 0)
            val now = System.currentTimeMillis() / 1000
            if (refreshExpiresAt < now) {
                return null
            }
            val expiresAt = sp.getLong("expiresAt", 0)
            return Token(accessToken, refreshToken, expiresAt = expiresAt)
        }

        fun clear(context: Context) : Boolean {
            return tokenSp(context).edit()
                .putString("accessToken", null)
                .putString("refreshToken", null)
                .putLong("expiresAt", 0)
                .putLong("refreshExpiresAt", 0)
                .commit()
        }

        private fun tokenSp(context: Context): SharedPreferences {
            return context.getSharedPreferences("token", Context.MODE_PRIVATE)
        }

    }


}